import { ElMessage } from 'element-plus'
import { encryptPhone } from '@/common/utils/common'
import { computed } from 'vue'
import { commonStore } from '@/common/store/modules/common'
import { getGender, createMethods } from '../utils/common'
import { deepClone } from '@/common/utils/common'

// pinia中获取数据
const region: any = computed(() => {
  // 地区
  return commonStore().publicCache.region || []
})
const areaMap: any = computed(() => {
  // 地区
  return commonStore().publicCache.areaMap || {}
})
const serviceLabelsObj: any = computed(() => {
  // 服务标签
  return commonStore().publicCache.serviceLabelsObj || {}
})
const userObj: any = computed(() => {
  // 员工
  return commonStore().publicCache.userCacheObj || {}
})
const globalFieldsObj: any = computed(() => {
  // 全局字段对象
  return commonStore().publicCache.globalFieldCacheObj || {}
})
const serviceLabels: any = computed(() => {
  // 服务标签
  const labels = deepClone(commonStore().publicCache.serviceLabels) || []
  const mapLabels = (arr: any) => {
    arr.forEach((v: any) => {
      v.disabled = !v.status // status: 1-启用 0-停用
      if (v.children && v.children.length) {
        mapLabels(v.children)
      }
    })
  }
  if (labels && labels.length) {
    mapLabels(labels)
  }
  return labels
})

const validateOther = (rule: any, arr: any, callback: any) => {
  // 手机号、QQ、邮箱、微信多个表单的必填校验
  let flag = false
  const newArr = arr || []
  newArr.forEach((item: any) => {
    if (item.value) {
      flag = true
    }
  })
  if (!flag) {
    callback(new Error('必填'))
  } else {
    callback()
  }
}

/*
 * 动态表单规则 fieldList: 获取的动态配置字段
 * */
export const getFormRules = (fieldList: any) => {
  const rules: any = {}
  fieldList.forEach((item: any) => {
    if (item.required) {
      if (item.type === 'pairs') {
        rules[item.field] = [
          {
            required: true,
            validator: validateOther,
            trigger: 'blur'
          }
        ]
      } else {
        rules[item.field] = [
          {
            required: true,
            trigger: 'blur',
            message: '必填'
          }
        ]
      }
    }
  })
  return rules
}

const defaultVal = (choices: any, type: string) => {
  let key = type === 'radio' ? '' : []
  const arr = choices.filter((v: any) => v.isDefault)
  if (arr && arr.length) {
    if (type === 'radio') {
      key = arr[0].key || ''
    } else {
      key = arr.map((i: any) => i.key) || []
    }
  }
  return key
}

/*
 * 动态表单类型处理
 * 跟进记录、服务小记需按顺序展示 所有类型均需初始化
 * */
export const handleType = (item: any, form: any, type: string) => {
  if (item.type === 'multi-select') {
    // 多选
    if (type === 'add' && !form[item.field]) {
      form[item.field] = defaultVal(item.choices || [], 'multi-select') // 初始化数据 | 默认数据
    } else if (!form[item.field]) {
      form[item.field] = [] // 编辑时详情接口未返回进行初始化
    }
    if (item.style === 'dropdown') {
      // 下拉
      item.type1 = 'dropdown'
      item.multiple = true
      item.defaultProps = { label: 'value', value: 'key' }
    } else if (item.style === 'tile') {
      // 平铺
      item.type1 = 'checkbox'
    }
  } else if (item.type === 'radio') {
    // 单选
    if (item.field === 'gender') {
      // 处理性别选项
      item.choices.forEach((v: any) => {
        v.value = getGender[v.key]
      })
    }
    if (type === 'add' && !form[item.field]) {
      form[item.field] = defaultVal(item.choices || [], 'radio') // 初始化数据 | 默认数据
    } else if (!form[item.field]) {
      form[item.field] = '' // 编辑时详情接口未返回进行初始化
    }
    if (item.style === 'dropdown') {
      item.type1 = 'dropdown'
      item.defaultProps = { label: 'value', value: 'key' }
    } else if (item.style === 'tile') {
      item.type1 = 'radio'
    }
  } else if (item.type === 'pairs') {
    // 文本（数组）
    if (!form[item.field] || !form[item.field].length) {
      form[item.field] = [{}] // 初始化数据
    }
    item.maxLength = 50
  } else if (item.type === 'cascade') {
    if (item.style === 'multi') {
      item.multiple = true
    }
    if (!form[item.field]) {
      // 新建或者编辑时详情接口未返回初始化数据
      form[item.field] = [] // 初始化数据
    }
    if (item.field === 'region') {
      // 省市区
      item.options = region.value || []
      item.defaultProps = {
        label: 'fullname',
        value: 'id'
      }
    } else if (item.field === 'serviceLabel') {
      // 服务标签
      item.options = serviceLabels.value || []
      item.defaultProps = {
        label: 'name',
        value: '_id'
      }
    } else if (item.options && item.options.level) {
      // 首次加载级联options处理
      item.fillLevel = item.options.fillLevel // 是否必选全部层级
      item.options = item.options && item.options.children
    }
  } else if (item.type === 'datetime' && item.style === 'day') {
    item.type1 = 'date'
    if (!form[item.field]) {
      // 新建或者编辑时详情接口未返回初始化数据
      form[item.field] = '' // 初始化数据
    }
  } else if (item.type === 'datetime-range' && item.style === 'day') {
    item.type1 = 'date-range'
    if (!form[item.field]) {
      // 新建或者编辑时详情接口未返回初始化数据
      form[item.field] = [] // 初始化数据
    }
  } else if (item.type === 'text') {
    item.maxLength = 50
    if (!form[item.field]) {
      // 新建或者编辑时详情接口未返回初始化数据
      form[item.field] = '' // 初始化数据
    }
  } else if (item.type === 'multi-text') {
    item.maxLength = 300
    if (!form[item.field]) {
      // 新建或者编辑时详情接口未返回初始化数据
      form[item.field] = '' // 初始化数据
    }
  } else if (item.type === 'attachment') {
    if (!form[item.field]) {
      // 新建或者编辑时详情接口未返回初始化数据
      form[item.field] = [] // 初始化数据
    }
  } else if (item.type === 'number') {
    if (!form[item.field]) {
      // 新建或者编辑时详情接口未返回初始化数据
      form[item.field] = undefined // 初始化数据
    }
  }
}

// 校验重复
const isSame = (arr: any) => {
  let same = false
  same = arr.some((item: any, index: number) => item.value === (arr[index + 1] && arr[index + 1].value))
  return same
}

const handleHideTel = (arr: any[]) => {
  // 手机号隐藏，在保存时候要匹配下，
  arr.forEach((item) => {
    if (item.value === encryptPhone(item.bakValue)) {
      // 如果当前的value跟bakValue处理之后的一样，说没做改动，请求后端存储，用bakValue
      item.value = item.bakValue
    }
    delete item.bakValue
  })
  return arr
}

// 编辑、新建时pairs为[{}] => []
export const handlePairs = (form: any) => {
  Object.keys(form).forEach((v) => {
    const obj = globalFieldsObj.value[v] || {}
    if (obj.type === 'pairs' && JSON.stringify(form[v]) === '[{}]') {
      form[v] = []
    }
    if (v === 'mobile') {
      // 手机号隐藏，在保存时候要匹配下
      form.mobile = handleHideTel(form.mobile || [])
    }
  })
}

/* type='pairs' 重复校验 */
export const validPairs = (form: any, fieldObj: any) => {
  const sameVal: any = []
  const text: any = []
  Object.keys(form).map((item) => {
    const obj = fieldObj[item]
    if (obj && obj.type === 'pairs') {
      if (form[item] && form[item].length > 1) {
        form[item] = form[item].filter((v: any) => v.value) // 去掉空值
        sameVal.push(isSame(form[item]))
        text.push(obj.name)
      } else if (JSON.stringify(form[item]) === '[{}]') {
        // 编辑、新建时pairs为[{}] => []
        form[item] = []
      }
      if (item === 'mobile' && form[item] && form[item].length && JSON.stringify(form[item]) !== '[{}]') {
        // 手机号隐藏，在保存时候要匹配下
        form.mobile = handleHideTel(form.mobile || [])
      }
    }
  })
  const tMessage = sameVal.findIndex((v: any) => v)
  if (tMessage > -1) {
    ElMessage.error(`${text[tMessage]}重复`)
    return false
  }
  return true
}

const handleCutomFile = (field: string, key: any, obj: any) => {
  // 处理table的自定义字段
  let str = ''
  if (obj) {
    if (['radio', 'cascade', 'multi-select'].includes(obj.type)) {
      // 多选 || 单选 || 级联
      let arr: any = []
      if (['cascade'].includes(obj.type)) {
        arr = (obj.options && obj.options.level ? obj.options.children : obj.options) || []
      } else {
        arr = obj.choices || []
      }
      let keyArr = key
      if (!Array.isArray(key)) {
        keyArr = [key]
      }
      const handleFn = (list: any, keyItem: string, lastOne?: boolean) => {
        if (list && list.length) {
          list.map((item: any) => {
            if (item.key === keyItem) {
              if (obj.type === 'cascade') {
                str += `${item.value + (lastOne ? ' ' : '/')}`
              } else {
                str += `${item.value} 、`
              }
            }
            if (item.children) {
              handleFn(item.children, keyItem, lastOne)
            }
          })
        }
      }
      keyArr.forEach((keyItem: string) => {
        if (Array.isArray(keyItem)) {
          // eg: 级联多选
          keyItem.forEach((v, i) => {
            const lastOne = i === keyItem.length - 1
            handleFn(arr, v, lastOne)
          })
        } else {
          handleFn(arr, keyItem)
        }
      })
      str = str.substring(0, str.length - 1)
    } else if (obj.type === 'pairs') {
      // 文本数组展示处理
      if (field === 'mobile') {
        str = key.map((v: any) => encryptPhone(v.value)).join('、')
      } else {
        str = key.map((v: any) => v.value).join('、')
      }
    } else if (['datetime-range'].includes(obj.type)) {
      // 时间范围
      if (key && key.length > 0) {
        str = `${key[0]} 至 ${key[1]}`
      }
    } else {
      str = key
    }
  }
  return str || '--'
}

// 字段展示处理
export const showFieldObj = (fieldObj: any, keyItem: string, item: any) => {
  if (keyItem === 'gender' && item[keyItem]) {
    // 性别
    item[keyItem] = getGender[item[keyItem]]
  } else if (
    ['firstCallUser', 'lastCallUser', 'lastChatUser', 'updateAgent', 'createAgent', 'firstOwner', 'owner'].includes(
      keyItem
    )
  ) {
    // 跟人有关的
    const agentObj = userObj.value[item[keyItem]]
    item[keyItem] = agentObj ? agentObj.agentName + '[' + agentObj.agentNumber + ']' : '--'
  } else if (keyItem === 'region') {
    // 省市县
    item[keyItem] = handleCascade(item[keyItem], 'areaMap')
  } else if (keyItem === 'serviceLabel') {
    // 服务标签
    item[keyItem] = handleCascade(item[keyItem], 'serviceLabelsObj')
  } else if (keyItem === 'createMethod' && item[keyItem]) {
    // 创建方式
    item[keyItem] = createMethods[item[keyItem]]
  } else {
    // 其他自定义字段
    item[keyItem] = handleCutomFile(keyItem, item[keyItem], fieldObj)
  }
}

// 匹配级联--省市区、服务标签
const handleCascade = (arr: any, cacheField: string) => {
  let str = ''
  const labels: any = [] // 服务标签颜色
  const handleFn = (list: any, lastOne?: boolean) => {
    let listStr = ''
    list.map((item: any, idx: number) => {
      if (item && Array.isArray(item)) {
        const lastOne = idx === list.length - 1
        handleFn(item, lastOne)
      } else {
        listStr += `${
          (cacheField === 'areaMap'
            ? areaMap.value[item]
            : serviceLabelsObj.value[item] && serviceLabelsObj.value[item].name) || ''
        }/`
        if (cacheField === 'serviceLabelsObj' && idx === list.length - 1) {
          // 服务标签的最后一个id
          labels.push({
            color: (serviceLabelsObj.value[item] && serviceLabelsObj.value[item].color) || '#fff',
            name: listStr.substring(0, listStr.length - 1)
          })
        }
      }
    })
    listStr = listStr.substring(0, listStr.length - 1)
    str += `${listStr + (lastOne ? '' : '、')}`
  }
  if (arr && Array.isArray(arr)) {
    handleFn(arr)
    str = str.substring(0, str.length - 1)
  }
  return cacheField === 'areaMap' ? (str ? str : '--') : labels
}

// 跟进记录、服务小记参数处理
export const getParams = (form: any) => {
  const fields: any = []
  const cloneForm = deepClone(form)
  Object.keys(cloneForm).forEach((item) => {
    const obj1: any = {} // 存储
    const obj2 = globalFieldsObj.value[item] // 匹配对应的字段
    /* eg: formData: { field: 'memo', name: '备注‘ } => defaultName: formData.name; defaultValue: form[item]; dynamicName: form.field; dynamicValue: defaultValue对应的key */
    obj1._id = obj2._id
    obj1.defaultName = obj2.name
    showFieldObj(obj2, item, cloneForm)
    obj1.defaultValue = cloneForm[item]
    fields.push(obj1)
  })
  return fields
}

// 附件预览的类型
export const handleFileType = (obj: any) => {
  const arr = obj.name.split('.')
  const name = arr[0]
  const suffix = arr[1]
  let type = ''
  // 附件预览类型
  if (['png', 'jpg', 'jpeg', 'gif'].includes(suffix)) {
    type = 'img'
  } else if (['mp4'].includes(suffix)) {
    type = 'video'
  } else if (['mp3', 'mav'].includes(suffix)) {
    type = 'audio'
  } else {
    type = suffix
  }
  return {
    url: obj.url,
    fileName: obj.name,
    name,
    suffix,
    type
  }
}
